<script setup>
import { getStudentInfoById, updateStudentInfo , getAcademyInfo,uploadProjectFile} from '@/api/student.js'
import { deleteProjectFile } from "@/api/project.js";
import {ref} from "vue";
import {useUserStore} from "@/stores/user.js";
import {ElMessage, ElMessageBox} from "element-plus";


const isEditMode = ref(false); // 是否处于编辑模式
const userStore = useUserStore()
const userId = userStore.userDetails.userId;
const academy_data = ref([]);


const currentStudent = ref({
  userId: null,
  userName: "",
  email: "",
  phone: "",
  account: "",
  className: "",
  gender: "",
  academy: "",
  description: "",
  avatar: "",
});

// 查询单个学生信息
const fetchStudentById = async () => {
  const response = await getStudentInfoById( userId );
  if (response.data.code === 200) {
    currentStudent.value = response.data.data;
  } else {
    ElMessage.error(response.data.msg);
  }
};
// 查询学院信息
const fetchAcademy = async () => {
  const response = await getAcademyInfo();
  if (response.data.code === 200) {
    academy_data.value = response.data.data;
  } else {
    ElMessage.error(response.data.msg);
  }
};



const enableEditMode = () => {
  isEditMode.value = true; // 启用编辑模式
};
// 保存学生信息
const handleSaveStudent = async () => {
  const response = await updateStudentInfo(currentStudent.value);
  if (response.data.code === 200) {
    ElMessage.success("修改成功");
    userStore.userDetails.userName = currentStudent.value.userName; // 更新用户信息
    userStore.userDetails.avatar = currentStudent.value.avatar; // 更新用户头像
    userStore.userDetails.phone = currentStudent.value.phone;
    isEditMode.value = false;
    await fetchStudentById();

   } else {
    ElMessage.error(response.data.msg);
  }
};

// 图片上传成功回调
const handleUploadSuccess = async (file) => {
  const formData = new FormData();
  formData.append("image", file.raw); // 获取图片文件
  formData.append("projectId", userId); // 添加项目 ID

  try {
    const response = await uploadProjectFile(formData);
    if (response.data.code === 200) {
      currentStudent.value.avatar = response.data.data; // 更新图片 URL
      ElMessage.success("图片上传成功！");
    } else {
      ElMessage.error(response.data.msg || "图片上传失败！");
    }
  } catch (error) {
    ElMessage.error("图片上传过程中发生错误！");
    console.error(error);
  }
};

// 删除图片
const handleDeleteImage = async (url) => {
  ElMessageBox.confirm("确认删除当前图片吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(async () => {
        try {
          const response = await deleteProjectFile(url);
          if (response.data.code === 200) {
              currentStudent.value.avatar = ""; // 清空图片 URL
            ElMessage.success("图片删除成功！");
          } else {
            ElMessage.error(response.data.msg || "图片删除失败！");
          }
        } catch (error) {
          ElMessage.error("图片删除过程中发生错误！");
          console.error(error);
        }
      })
      .catch(() => {
        ElMessage.info("已取消删除图片");
      });
};
 fetchAcademy();
fetchStudentById();


</script>


<template>
  <div class="profile-container">
    <el-form
        :model="currentStudent"
        label-width="100px"
        class="profile-form"
    >
      <el-form-item label="姓名">
        <el-input v-model="currentStudent.userName" :disabled="!isEditMode" />
      </el-form-item>
      <el-form-item label="头像">
        <div class="image-upload-container">
          <img
              :src="currentStudent.avatar || 'https://via.placeholder.com/300x200'"
              alt="头像"
              class="profile-image"
          />
          <div class="upload-buttons">
            <el-upload
                :on-change="handleUploadSuccess"
                :show-file-list="false"
                accept="image/*"
            >
              <el-button
                  size="small"
                  type="primary"
                  :disabled="!isEditMode"
              >
                上传图片
              </el-button>
            </el-upload>
            <el-button
                size="small"
                type="danger"
                :disabled="!currentStudent.avatar || !isEditMode"
                @click="handleDeleteImage(currentStudent.avatar)"
                style="margin-top: 5px"
            >
              删除图片
            </el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="currentStudent.email" :disabled="!isEditMode" />
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="currentStudent.phone" :disabled="!isEditMode" />
      </el-form-item>
      <el-form-item label="班级">
        <el-input v-model="currentStudent.className" :disabled="!isEditMode" />
      </el-form-item>
      <el-form-item label="性别">
        <el-select
            v-model="currentStudent.gender"
            :disabled="!isEditMode"
            placeholder="请选择性别"
        >
          <el-option label="男" value="男"></el-option>
          <el-option label="女" value="女"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学院">
        <el-select
            v-model="currentStudent.academy"
            :disabled="!isEditMode"
            placeholder="请选择学院"
        >
          <el-option
              v-for="academy in academy_data"
              :key="academy.id"
              :label="academy.academyName"
              :value="academy.academyName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="描述">
        <el-input
            v-model="currentStudent.description"
            :disabled="!isEditMode"
            type="textarea"
        />
      </el-form-item>
    </el-form>

    <div class="form-actions">
      <el-button
          v-if="!isEditMode"
          type="primary"
          @click="enableEditMode"
      >
        修改信息
      </el-button>
      <el-button
          v-else
          type="success"
          @click="handleSaveStudent"
      >
        保存信息
      </el-button>
    </div>
  </div>
</template>


<style scoped>
.profile-container {
  width: 140%;
   margin: 20px auto;
  padding: 20px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.profile-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.profile-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  border: 2px solid #409eff;
  margin-right: 15px;
}

.profile-header-info h2 {
  margin: 0;
  font-size: 1.5rem;
  color: #333;
}

.profile-header-info p {
  margin: 5px 0 0;
  color: #666;
}

.profile-form {
  margin-top: 20px;
}

.profile-image {
  width: 300px;
  height: 200px;
  border-radius: 10px;
  border: 1px solid #ddd;
  object-fit: cover;
  margin-bottom: 10px;
}

.image-upload-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.upload-buttons {
  display: flex;
  gap: 10px;
}

.form-actions {
  display: flex;
  gap: 10px;
  margin-top: 20px;
  margin-left: 45%;
}

.el-button {
  border-radius: 20px;
}

.el-button--primary {
  background: linear-gradient(45deg, #409eff, #66b1ff);
  border: none;
}

.el-button--success {
  background: linear-gradient(45deg, #67c23a, #85d48a);
  border: none;
}

.el-button--danger {
  background: linear-gradient(45deg, #f56c6c, #fb8e8e);
  border: none;
}
</style>
